package com.mail.anteater.util;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import java.util.Queue;

import javax.swing.Timer;

import org.apache.log4j.Logger;

public class ThreadQueue implements ActionListener {
	final static Logger logger = Logger.getLogger(ThreadQueue.class);
	
	private Queue<Thread> processQueue = new LinkedList<Thread>(); 
	
	private long maxAliveTime = 5000;
	private Timer timer = new Timer((int)maxAliveTime, this);
	
	public void enqueue(Thread thread){
		if(processQueue.size() > 0 && !isThreadExist(thread)){
			processQueue.offer(thread);
			try {
				synchronized(thread){
					thread.wait();	
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}else{
			if(timer != null  && !isThreadExist(thread)){
				processQueue.offer(thread);
				timer.restart();
			}
		}
	}

	public void complete(){
		if(timer != null){
			if(timer.isRunning()){
				timer.stop();	
			}	
		}
		dequeue();
		if(peekQueue() != null){
			synchronized(peekQueue()){
				peekQueue().notify();	
			}	
		}
	}
	
	public Thread dequeue(){
		synchronized(processQueue){
			return processQueue.poll();
		}
	}
	
	public Thread peekQueue(){
		synchronized(processQueue){
			return processQueue.peek();	
		}
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(timer != null){
			if(timer.isRunning()){
				timer.stop();	
			}	
		}
		dequeue();
		if(peekQueue() != null){
			synchronized(peekQueue()){
				peekQueue().notify();
				timer.restart();
			}
		}
	}
	
	private boolean isThreadExist(Thread thread){
		if(thread == null){
			return false;
		}else{
			for(Thread t : processQueue){
				if(t != null){
					if(t.getId() == thread.getId()){
						return true;
					}	
				}
			}	
		}
		return false;
	}
}
